Shader "Prota/BlurHorizontal"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" { }
        _Mask ("Mask", 2D) = "white" { }
        _MaskWeight ("Mask Weight", Float) = 1.0
        _MaskConstant ("Mask Constant", Float) = 0.0
        _Size ("Size", Float) = 6.0
        _Step ("Step", Int) = 1
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_TexelSize;
            
            sampler2D _Mask;
            float _MaskWeight;
            float _MaskConstant;
            
            float _Size;
            float _Step;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                return o;
            }

            float Gaussian(float x, float sigma)
            {
                return exp(- (x * x) / (2.0 * sigma * sigma)) / (sqrt(2.0 * 3.14159) * sigma);
            }

            fixed4 frag (v2f i) : SV_Target
            {
                float2 uv = i.uv;
                float4 color = float4(0, 0, 0, 0);
                float total = 0.0;
                float2 blurSize = _Size * _MainTex_TexelSize.xy;

                float kernelRadius = ceil(3.0 * _Size); // 3 sigma rule

                _Step = max(kernelRadius * 2 / 100, _Step);
                if(_Step < 0) discard;
                
                float mask = tex2D(_Mask, uv).r;
                mask = sqrt(mask);
                mask *= _MaskWeight;
                mask += _MaskConstant;
                
                for (float x = -kernelRadius; x <= kernelRadius; x += _Step)
                {
                    // 颜色是从周围扩散过来的.
                    float2 delta = float2(x, 0) * blurSize.x;
                    float weight = Gaussian(x, _Size);
                    color += tex2D(_MainTex, uv + delta * mask) * weight;
                    total += weight;
                }
                color /= total;

                return color;
            }
            ENDCG
        }
    }
    FallBack "Diffuse"
}
